package com.blacktech.dbu.auth.repository;

import com.blacktech.dbu.auth.entity.DbuUser;
import com.blacktech.dbu.core.dict.UserStatus;
import com.blacktech.dbu.core.dict.UserType;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;

/**
 * 用户数据访问层
 *
 * @author Yanyunsong
 */
@Repository
public interface UserRepository extends JpaRepository<DbuUser, Long>, JpaSpecificationExecutor<DbuUser> {

    /**
     * 根据用户名查找用户
     */
    Optional<DbuUser> findByUsername(String username);

    /**
     * 根据用户名和状态查找用户
     */
    Optional<DbuUser> findByUsernameAndStatus(String username, UserStatus status);

    /**
     * 检查用户名是否存在
     */
    boolean existsByUsername(String username);

    /**
     * 检查邮箱是否存在
     */
    boolean existsByEmail(String email);

    /**
     * 根据用户类型查找用户
     */
    List<DbuUser> findByUserType(UserType userType);

    /**
     * 根据状态查找用户
     */
    List<DbuUser> findByStatus(UserStatus status);

    /**
     * 查找被锁定且锁定时间已过期的用户
     */
    @Query("SELECT u FROM DbuUser u WHERE u.status = 'LOCKED' AND u.lockedTime < :threshold")
    List<DbuUser> findLockedUsersWhoseLockExpired(@Param("threshold") LocalDateTime threshold);

    /**
     * 根据显示名称模糊查询
     */
    @Query("SELECT u FROM DbuUser u WHERE u.displayName LIKE %:displayName%")
    Page<DbuUser> findByDisplayNameContaining(@Param("displayName") String displayName, Pageable pageable);

    /**
     * 多条件查询用户
     */
    @Query("SELECT u FROM DbuUser u WHERE " +
           "(:username IS NULL OR u.username LIKE %:username%) AND " +
           "(:displayName IS NULL OR u.displayName LIKE %:displayName%) AND " +
           "(:userType IS NULL OR u.userType = :userType) AND " +
           "(:status IS NULL OR u.status = :status)")
    Page<DbuUser> findUsersByConditions(@Param("username") String username,
                                       @Param("displayName") String displayName,
                                       @Param("userType") UserType userType,
                                       @Param("status") UserStatus status,
                                       Pageable pageable);

    /**
     * 更新用户最后登录时间
     */
    @Modifying
    @Query("UPDATE DbuUser u SET u.lastLoginTime = :loginTime WHERE u.id = :userId")
    int updateLastLoginTime(@Param("userId") Long userId, @Param("loginTime") LocalDateTime loginTime);

    /**
     * 更新用户登录失败次数
     */
    @Modifying
    @Query("UPDATE DbuUser u SET u.loginFailedCount = :failedCount WHERE u.id = :userId")
    int updateLoginFailedCount(@Param("userId") Long userId, @Param("failedCount") Integer failedCount);

    /**
     * 重置用户登录失败次数
     */
    @Modifying
    @Query("UPDATE DbuUser u SET u.loginFailedCount = 0, u.lockedTime = null, u.status = 'ENABLED' WHERE u.id = :userId")
    int resetLoginFailedCount(@Param("userId") Long userId);

    /**
     * 锁定用户账户
     */
    @Modifying
    @Query("UPDATE DbuUser u SET u.status = 'LOCKED', u.lockedTime = :lockedTime WHERE u.id = :userId")
    int lockUser(@Param("userId") Long userId, @Param("lockedTime") LocalDateTime lockedTime);
}